1.两个字符串放在一起会自动合并
"Let's say " '"Hello, world!"' --->'Let/'s say "Hello, world!"'
但是两个字符串变量放在一起中间要加“+”号才会合并
2.str与repr
str会将变量转化成某种用户能够理解的String方式,如
print str(10000L) --->10000
#str(object) -- Converts a value to a string
repr会将变量转化为Python的合法变量
print repr(10000L) --->10000L
另外repr(x)='x'
#repr(object) -- Returns a string representation of a value
3.input与raw_input
name = input("What is your name? ")回车继续
What is your name? Gumby
会出错,因为input会假设你输入的是有效的Python变量,而此处Gumby未定义。改为
What is your name? 'Gumby'则成功
#input(prompt) -- Gets input from the user
name = raw_input("What is your name? ")回车继续
What is your name? Gumby 则不会报错,因为raw_input会认为输入的均为String
#raw_input(prompt) -- Gets input from the user, as a string
4.'''与r与u
'''长字符串''' 中间可以分行,可以任意用'、"
r前缀为Raw String, 'Hello /nthyU!'会分行,而r'Hello /nthyU!'就忠实于WhatYouSeeIsWhatYouGet,
u前缀为Unicode String,每个字符用16Bit。
"Let's say " '"Hello, world!"' --->'Let/'s say "Hello, world!"'
但是两个字符串变量放在一起中间要加“+”号才会合并
2.str与repr
str会将变量转化成某种用户能够理解的String方式,如
print str(10000L) --->10000
#str(object) -- Converts a value to a string
repr会将变量转化为Python的合法变量
print repr(10000L) --->10000L
另外repr(x)='x'
#repr(object) -- Returns a string representation of a value
3.input与raw_input
name = input("What is your name? ")回车继续
What is your name? Gumby
会出错,因为input会假设你输入的是有效的Python变量,而此处Gumby未定义。改为
What is your name? 'Gumby'则成功
#input(prompt) -- Gets input from the user
name = raw_input("What is your name? ")回车继续
What is your name? Gumby 则不会报错,因为raw_input会认为输入的均为String
#raw_input(prompt) -- Gets input from the user, as a string
4.'''与r与u
'''长字符串''' 中间可以分行,可以任意用'、"
r前缀为Raw String, 'Hello /nthyU!'会分行,而r'Hello /nthyU!'就忠实于WhatYouSeeIsWhatYouGet,
u前缀为Unicode String,每个字符用16Bit。
字符串操作技巧
本文介绍了Python中字符串的基本操作,包括字符串的合并、转换方法str与repr的区别、不同输入方式input与raw_input的应用场景以及长字符串的定义方式。通过本文,读者可以了解如何更高效地处理字符串。
162

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



