1.单引号' '与双引号" "的运用
print('I told my friend, "Python is my favorite language!"')
print("The language 'Python' is named after Monty Python, not the snake.")
print("One of Python's strengths is its diverse and supportive community.")
输出结果:
I told my friend, "Python is my favorite language!"
The language 'Python' is named after Monty Python, not the snake.
One of Python's strengths is its diverse and supportive community.
2.修改字符串的大小写
name = 'my name is python'
print(name.title()) #首字母大写
print(name.upper()) #全部大写
name = 'MY NAME IS PYTHON'
print(name.lower()) #全部小写
输出结果:
My Name Is Python MY NAME IS PYTHON my name is python
3.拼接字符串
first_para = 'Hello'
last_para = 'World'
full_para = first_para + ' ' + last_para
print(full_para)
输出结果:Hellow World
利用format()函数也可以实现拼接
params = "{} {}".format('Hellow','World')
print(params)
#format(),格式化函数,后面有机会再说
输出结果:Hellow World
4.删除字符串中多余的空白
first_word = ' python '
last_word = 'PHP'
print(first_word + 'And' + last_word)
print(first_word.rstrip() + 'And' + last_word) #去掉右边的空白
print(first_word.lstrip() + 'And' + last_word) #去掉左边的空白
print(first_word.strip() + 'And' + last_word) #去掉两边的空白
输出结果:
python AndPHP
pythonAndPHP
python AndPHP
pythonAndPHP
本文深入讲解了Python中字符串的各种操作技巧,包括单引号与双引号的使用、大小写转换、字符串拼接及空白字符的处理。通过具体示例,读者可以掌握如何灵活运用这些技巧来提高编程效率。
512

被折叠的 条评论
为什么被折叠?



